﻿using Noesis.Javascript;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace MO.BusinessServer
{
    public class ListManager : BaseManager
    {
        public ListManager(object context)
        {
            base.Init(context);
        }
        public ListData GetListData(string code)
        {
            var def = DataManager.FindListByListCode(code);
            def.QuerySql = def.QuerySql.Replace("[UserCode]", this.Context.User.Code);
            DataTable table = DbOperation.DB.ExecuteDataTable(def.QuerySql);
            ListData result = new ListData();
            result.Name = def.Name;
            result.ViewTemplate = def.ViewTemplate;
            foreach (DataRow row in table.Rows)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                    dict[col.ColumnName] = row[col];
                result.Datas.Add(dict);
            }
            SysOperation sys = new SysOperation() { User = this.Context.User };
            JavascriptContext jsRun = new JavascriptContext();
            jsRun.SetParameter("Datas", result.Datas);
            jsRun.SetParameter("Sys", sys);
            jsRun.Run(def.QueryScript);
            result.Datas = ((object[])jsRun.GetParameter("Datas")).Select(t=>(Dictionary<string, object>)t).ToList();
            return result;
        }
    }
    public class ListData
    {
        public string Name;
        public string ViewTemplate;
        public List<Dictionary<string, object>> Datas = new List<Dictionary<string, object>>();
    }
}
